import axios from 'axios'
import qs from 'qs';
export async function request({
  method = 'GET', //默认为GET请求
  url,
  data
}) {
  try {
    let baseUrl = ''
    const headers = new Headers()
    if (method === 'POST' || method === 'post') {
      headers['Content-Type'] = 'application/json;charset=utf-8'
    }
    let actPrefixUrl = '/activity'
    let stationPlatPrefixUrl = '/station-platform'
    const stationCenterPrefixUrl = '/station-center'  //油站数据1.0看板前缀
    let cwxtPrefixUrl = '/cwxt'
    let responseType = 'json'
    //console.log('前缀名', cwxtPrefixUrl)
    let createConfig = {}
    if (process.env.NODE_ENV === 'development') {
      if (url.indexOf(actPrefixUrl) != -1) {
        baseUrl = actPrefixUrl
      }
      else if (url.indexOf(cwxtPrefixUrl) != -1) {
        console.log('本地调试环境走财务系统前缀')
        baseUrl = cwxtPrefixUrl
      }
      //让本地取映射8081的端口的接口地址
      else if (url.indexOf(stationPlatPrefixUrl) != -1) {
        baseUrl = stationPlatPrefixUrl
      } else if (url.indexOf(stationCenterPrefixUrl) != -1) {
        console.log('走station-center的前缀')
        baseUrl = stationCenterPrefixUrl
      }
      createConfig = {
        // withCredentials: true, // send cookies when cross-domain requests
        timeout: 15000, // request timeout
        headers: headers,
        responseType: responseType,
        // responseEncoding: 'utf8', // default
      }
    } else if (process.env.NODE_ENV === 'production') {
      console.log('生产环境地址打印', baseUrl)
      createConfig = {
        baseURL: baseUrl,
        // withCredentials: true, // send cookies when cross-domain requests
        timeout: 15000, // request timeout
        headers: headers,
        responseType: responseType,
        // responseEncoding: 'utf8', // default
      }
    }

    // create an axios instance
    const instance = axios.create()
    // request interceptor
    instance.interceptors.request.use(
      config => {
        // do something before request is sent
        // console.log('打印拦截器', config)
        return config
      },
      error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
      }
    )
    url = baseUrl + url
    console.log('url的后半段地址会有重复', url)
    let response
    if (method === 'GET' || method === 'get') {
      //console.log('responseGet', response)
      const getUrl = `${url}${data ? `?${qs.stringify(data)}` : ''}`
      response = await instance.get(getUrl)
    } else if (method === 'POST' || method === 'post') {
      //const jsonString = JSON.stringify(data)
      response = await instance.post(url, data)
    } else if (method === 'PUT' || method === 'put') {
      const jsonString = JSON.stringify(data)
      response = await instance.put(url, jsonString)
    } else if (method === 'DELETE' || method === 'delete') {
      const deleteUrl = `${url}${data ? `?${qs.stringify(data)}` : ''}`
      response = await instance.delete(deleteUrl)
    }
    // response interceptor
    // instance.interceptors.response.use(
    //   /**
    //    * If you want to get http information such as headers or status
    //    * Please return  response => response
    //   */

    //   /**
    //    * Determine the request status by custom code
    //    * Here is just an example
    //    * You can also judge the status by HTTP Status Code
    //    */
    //   (response) => {
    //     console.log('网络请求响应response',response)
    //     const res = response.data
    //     // if the custom code is not 20000, it is judged as an error.
    //     if (res.code !== 20000) {
    //       Message({
    //         message: res.message || 'Error',
    //         type: 'error',
    //         duration: 5 * 1000
    //       })

    //       // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
    //       if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
    //         // to re-login
    //         MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
    //           confirmButtonText: 'Re-Login',
    //           cancelButtonText: 'Cancel',
    //           type: 'warning'
    //         }).then(() => {
    //           store.dispatch('user/resetToken').then(() => {
    //             location.reload()
    //           })
    //         })
    //       }
    //       return Promise.reject(new Error(res.message || 'Error'))
    //     } else {
    //       return res
    //     }
    //   },
    //   error => {
    //     console.log('err' + error) // for debug
    //     Message({
    //       message: error.message,
    //       type: 'error',
    //       duration: 5 * 1000
    //     })
    //     return Promise.reject(error)
    //   }
    // 

    // if (url.indexOf(targetUrl) != -1) {
    //   console.log('response', response)
    //   window.open(response.data)
    //   const blobContent= response.data
    //   console.log('blobContent',blobContent)
    //   //window.URL.createObjectURL(blob);
    //   //const blobUrl = window.URL.createObjectURL(blobContent)
    //   download(blobContent)
    //   //downloadFileByBlob(blobUrl, 'config.j')
    //   return;
    // }
    return response.data
  } catch (err) {
    console.log('网络请求catch_err', err)
    if (err.response && err.response.data) {
      //await Storage.remove('user')
      //navigate('/login');
      return {}
    }
    if (err.response && err.response.status === 400) {
      return err.response.data
    }
    // 请求超时
    // if (err.request && err.request.readyState === 4 && err.request.status === 0) {
    //   Toast.show('error', LANG['网络连接失败'] || '网络连接失败', 2000)
    // }
    return {}

  }
}
export default request
